package com.bwie.auth.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTUtil;
import com.alibaba.nacos.common.utils.UuidUtils;
import com.bwie.auth.remote.RemoteSystemService;
import com.bwie.auth.service.AuthService;
import com.bwie.common.constants.JwtConstants;
import com.bwie.common.constants.TokenConstants;
import com.bwie.common.domain.User;
import com.bwie.common.domain.request.UserReqLogin;
import com.bwie.common.domain.request.UserReqSignUp;
import com.bwie.common.exceptions.BizException;
import com.bwie.common.result.Result;
import com.bwie.common.utils.JwtUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @Author Junchen_N1
 * @Date 2025/6/17 9:18
 * @ClassName AuthServiceImpl
 * @Description TODO
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    /**
     * 登录
     * @param userReqLogin
     * @return
     */
    @Override
    public Result<String> login(UserReqLogin userReqLogin) {
        //所有参数校验均使用validation
        User loginUser = RemoteSystemService.selectUserByUsernameAndPassword(userReqLogin);
        if (ObjectUtil.isEmpty(loginUser)){
            throw new BizException("用户名密码不匹配");
        }

        //JWT技术生成token
        Map<String,Object> map = new HashMap<>();
        String userKey = UuidUtils.generateUuid();
        map.put(JwtConstants.USER_KEY,userKey);
        String token = JwtUtils.createToken(map);

        redisTemplate.opsForValue().set(TokenConstants.LOGIN_TOKEN_KEY+userKey,loginUser,30, TimeUnit.MINUTES);

        //查询当前用户好友信息
        List<User> friendList = RemoteSystemService.selectUserFriendsListByUserId(loginUser.getUserId());
        redisTemplate.opsForSet().add(TokenConstants.FRIENDS_KEY+loginUser.getUserId(),friendList);
        redisTemplate.expire(TokenConstants.FRIENDS_KEY+loginUser.getUserId(),30,TimeUnit.MINUTES);
        return Result.success(token);
    }

    /**
     * 注册
     * @param userReqSignUp
     */
    @Override
    public void signUp(UserReqSignUp userReqSignUp) {
        //校验手机号和用户名唯一性
        if (ObjectUtil.isNotEmpty(RemoteSystemService.selectUserByUsername(userReqSignUp.getUsername()))) {
            throw new BizException("用户名称已注册，请重试");
        }
        if (ObjectUtil.isNotEmpty(RemoteSystemService.selectUserByTel(userReqSignUp.getTel()))) {
            throw new BizException("手机号已注册，请重试");
        }
        //校验验证码是否正确
        if (Boolean.FALSE.equals(redisTemplate.hasKey(TokenConstants.SMS_CODE + userReqSignUp.getCode()))){
            throw new BizException("验证码输入错误或已过期");
        }
        //添加数据库
        RemoteSystemService.addUser(userReqSignUp);
    }
}
